﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using FreightSoft.Classes;
using System.Net.Http;
using System.Xml.Linq;
using System.Threading.Tasks;

namespace FreightSoft.Classes
{
    public class Weather
    {
        private static string AppID = "PLACE-YOUR-APP-ID-HERE";

        public List<WeatherDetails> GetWeather(double lat, double lon, int cnt)
        {
            string url = string.Format
                ("http://api.openweathermap.org/data/2.5/forecast/daily?lat={0}&lon={1}&type=accurate&mode=xml&units=metric&cnt={2}&appid={3}",
                lat,lon, cnt, AppID);
            //api.openweathermap.org/data/2.5/forecast/daily?q=London&mode=xml&units=metric&cnt=7
            //api.openweathermap.org/data/2.5/forecast/daily?lat=35&lon=139&cnt=10&mode=json
            using (HttpClient client = new HttpClient())
            {
                try
                {
                    string response = client.GetStringAsync(url).Result;
                    if (!(response.Contains("message") && response.Contains("cod")))
                    {
                        XElement xEl = XElement.Load(new System.IO.StringReader(response));
                        return GetWeatherInfo(xEl);
                    }
                    else
                    {
                        return new List<WeatherDetails>();
                    }
                }
                catch (HttpRequestException)
                {
                    return new List<WeatherDetails>();
                }
            }
        }

        private static List<WeatherDetails> GetWeatherInfo(XElement xEl)
        {
            //string location_ = xEl.Descendants("location").Elements("name").ToString();
            string location_ = (from el in xEl.Elements("location") select el.Element("name").Value).ToList().First();

            IEnumerable<WeatherDetails> w = xEl.Descendants("time").Select((el) =>
                new WeatherDetails
                {
                    Location = location_.Length > 12 ? location_.Substring(0, 13) : location_,
                    Humidity = el.Element("humidity").Attribute("value").Value + "%",
                    MaxTemperature = el.Element("temperature").Attribute("max").Value + "°",
                    MinTemperature = el.Element("temperature").Attribute("min").Value + "°",
                    Temperature = el.Element("temperature").Attribute("day").Value + "°",
                    Weather = el.Element("symbol").Attribute("name").Value,
                    WeatherNumber = el.Element("symbol").Attribute("number").Value,
                    WeatherDay = Day(el),                   
                    WeatherIcon = WeatherIconPath(el),
                    WindDirection = el.Element("windDirection").Attribute("name").Value,
                    WindSpeed = el.Element("windSpeed").Attribute("mps").Value + "mps"
                });

            return w.ToList();
        }

        private static string DayOfTheWeek(XElement el)
        {
            DayOfWeek dW = Convert.ToDateTime(el.Attribute("day").Value).DayOfWeek;
            return dW.ToString();
        }

        private static string Day(XElement el)
        {
            DateTime dW = Convert.ToDateTime(el.Attribute("day").Value).Date;
            return dW.ToShortDateString();
        }

        private static string WeatherIconPath(XElement el)
        {
            string symbolVar = el.Element("symbol").Attribute("var").Value;
            string symbolNumber = el.Element("symbol").Attribute("number").Value;
            string dayOrNight = symbolVar.ElementAt(2).ToString(); // d or n
            //return String.Format("WeatherIcons/{0}{1}.png", symbolNumber, dayOrNight);
            return String.Format("http://openweathermap.org/img/w/{0}.png", symbolVar);           
        }
    }    
}